package com.smartcommunity.service.village.impl;

import com.smartcommunity.entity.village.Tree;

import java.util.ArrayList;
import java.util.List;

public class TreeUtil {

    /**
     * 两层循环实现建树
     *
     * @param treeNodes 传入的树节点列表
     * @return
     */
    public <T extends Tree> List<T> build(List<T> treeNodes, Object root) {

        List<T> trees = new ArrayList<>();
        for (T treeNode : treeNodes) {

            if (root.equals(treeNode.getParentId())) {
                trees.add(treeNode);
            }

            for (T it : treeNodes) {
                if (it.getParentId() == treeNode.getId()) {
                    if (treeNode.getItems() == null) {
                        treeNode.setItems(new ArrayList<>());
                    }
                    treeNode.getItems().add(it);
                }
            }
        }
        return trees;
    }

    /**
     * 使用递归方法建树
     *
     * @param treeNodes
     * @return
     */
    public <T extends Tree> List<T> buildByRecursive(List<T> treeNodes, Object root) {
        List<T> trees = new ArrayList<T>();
        for (T treeNode : treeNodes) {
            if(root==null){
                if (treeNode.getParentId()==null) {
                    trees.add(findChildren(treeNode, treeNodes));
                }
            }else{
                if (root.equals(treeNode.getParentId())) {
                    trees.add(findChildren(treeNode, treeNodes));
                }
            }
        }
        return trees;
    }

    /**
     * 递归查找子节点
     *
     * @param treeNodes
     * @return
     */
    public <T extends Tree> T findChildrens(T treeNode, List<T> treeNodes) {
        for (T it : treeNodes) {
            if (treeNode.getId().equals(it.getParentId())) {
                if (treeNode.getItems() == null) {
                    treeNode.setItems(new ArrayList<>());
                }
                treeNode.getItems().add(findChildren(it, treeNodes));
            }
        }
        return treeNode;
    }

    /**
     * 递归查找子节点
     *
     * @param treeNodes
     * @return
     */
    public <T extends Tree> T findChildren(T treeNode, List<T> treeNodes) {
        for (T it : treeNodes) {
            if (treeNode.getId().equals(it.getParentId())) {
                if (treeNode.getItems() == null) {
                    treeNode.setItems(new ArrayList<>());
                }
                treeNode.getItems().add(findChildren(it, treeNodes));
            }
        }
        return treeNode;
    }
}
